package com.jizhangben.controller;

import com.jizhangben.pojo.AccountPojo;
import com.jizhangben.pojo.UserPojo;
import com.jizhangben.service.AccountService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;;

@WebServlet("/insert")
public class InsertAccountServlet extends HttpServlet {
    private AccountService accountService = new AccountService();

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("views/insert.jsp").forward(req, resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            HttpSession session = req.getSession();
            String accountName = req.getParameter("accountName");
            String accountMoney = req.getParameter("accountMoney");
            String accountDetails = req.getParameter("accountDetails");
            AccountPojo accountPojo = new AccountPojo();
            accountPojo.setName(accountName);
            if(accountMoney.length()==0){
                accountPojo.setMoney(0);
            }else{
                accountPojo.setMoney(Double.parseDouble(accountMoney));
            }
            accountPojo.setDetails(accountDetails);
            accountPojo.setUserId(((UserPojo) session.getAttribute("user")).getId());
            java.util.Date utilDate = new java.util.Date();
            accountPojo.setTime(new java.sql.Date(utilDate.getTime()));
            int result = accountService.insertAccount(accountPojo);
            if (result <= 0) {
                // 修改失败的情况下
                req.setAttribute("errorMsg", "添加失败!");
                return;
            }
            resp.sendRedirect(req.getContextPath() + "/account");
        } catch (Exception e) {
            e.printStackTrace();
            // 修改失败的情况下
            resp.sendRedirect(req.getContextPath() + "/insert");
            req.setAttribute("errorMsg", "系统错误!");
        }
    }
}
